/**
 * created by zhouli on 2018/12/20
 * 角色（职能）菜单管理
 * todo
 * 某些菜单可以操作只读与操作，有些菜单不行，需要后端加字段
 */
import React from 'react';
import {connect} from 'react-redux';
import {Icon, Modal, Button, Input, Select, Tree, Popover, Spin, message} from 'antd';
import 'styles/permission-setting/role-menu-setting/role-menu-setting.scss';
import RSService from 'containers/permission-setting/role-menu-setting/role-menu-setting.service';
import {deepFullCopy, messages, trim} from "share/common";
import RoleMenu from 'containers/permission-setting/components/role-menu';

const Search = Input.Search;
const Option = Select.Option;
const {TreeNode} = Tree;

class RoleMenuSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      editAble: false,
      cRole: {},//当前角色
      adminTree: [],//可被分配：管理员菜单
      financeTree: [],//可被分配：财务菜单
      otherTree: [],//可被分配: 其他
      treeDataLoading: true,
      expandedKeysRole: [],
      autoExpandParentRole: true,
      selectedKeysRole: [],
      cNode: {},
      // selectedKeys: [],
      allWithCheckedList: [],
      allWithCheckedTree: [],
      allWithCheckedListCopy: [],//用来执行取消
      originCheckedListCopy: [],//用来挑选变化的值
    }
  }

  componentDidMount() {
  }

  //角色被选择的回调
  itemSelect = (_key, data) => {
    let {treeDataLoading, cRole} = this.state;
    this.setState({
      treeDataLoading: true,
      cRole: (_key && data) ? data : {},
      cNode: {}
    }, () => {
      if ((_key && data)) {
        let cRole = this.state.cRole;//必须拿到设置之后的，不然是空对象
        let getAllPermissionTreeParams = {
          resourceId: 0,
          categoryType: cRole.permissionCategory
        };
        let getPermissionTreeParams = {
          permissionId: cRole.id
        };
        RSService.mergeAllMenus(getAllPermissionTreeParams, getPermissionTreeParams)
          .then(res => {
            let allWithCheckedListInstance = RSService.listTranformTree(res[0]);
            let allMenus = this.handleCheckedAndShow(allWithCheckedListInstance.getResult());
            this.setState({
              treeDataLoading: false,
              editAble: false,
              allWithCheckedList: allWithCheckedListInstance.getOrigin(),
              allWithCheckedTree: allMenus,
              allWithCheckedListCopy: deepFullCopy(res[0]),//用来执行取消
              originCheckedListCopy: deepFullCopy(res[1]),//用来挑选变化的值
            })
          })
      }
    })
  };

  handleCheckedAndShow = (allMenus) => {
    allMenus.map((item, index) => {
      if(item.hasChild && (!item.children || !item.children.length)){
        allMenus.splice(index, 1);
      }
      if(item.children && item.children.length){
        let bool = item.children.every(item => !item.__checked);
        if (bool) item.__checked = false;
      }
    });
    return allMenus;
  };

  //展开当前角色
  onExpandRole = (expandedKeys) => {
    this.setState({
      expandedKeysRole: expandedKeys,
      autoExpandParentRole: false,
    });
  };
  //选择功能菜单执行回调
  onSelectRole = (selectedKeys, info) => {
    this.setState({
      selectedKeysRole: selectedKeys,
      cNode: info.node.props.dataRef
    });
  };
  //搜索当前角色菜单
  fiterRoleList = (e) => {
    let val = trim(e.target.value);
    let allWithCheckedList = this.state.allWithCheckedList;
    let resTreeInstance = RSService.listTranformTree(allWithCheckedList);
    let expandedKeysRole = [];
    if (val && val.length && val.length > 0) {
      expandedKeysRole = resTreeInstance.getOrigin().map(item => {
        return item.key;
      });
    } else {
      expandedKeysRole = [];
    }
    this.setState({
      expandedKeysRole,
      allWithCheckedTree: resTreeInstance.getSuperFilterTree(val),//隐藏非匹配结果（匹配结果父级菜单不隐藏）
    })
  };
  //修改菜单权限
  handleRoleOptionChange = (e) => {
    let cNode = this.state.cNode;
    cNode.operationType = e;
    this.updatePermissionTreeNode(cNode);
    this.setState({
      cNode
    })
  };
  // 当前角色树----end------
  //保存功能
  handleSaveFun = () => {
    let {cRole, originCheckedListCopy, allWithCheckedList} = this.state;
    let currentCheckedList = [];
    let currentUnCheckedList = [];
    allWithCheckedList.map(item => {
      if (item.__checked) {
        currentCheckedList.push(item)
      } else {
        currentUnCheckedList.push(item)
      }
    });
    /*
    * 涉及到求并集，交集，原本被勾选-现在勾选的-现在没有被勾选
    * 选出将要被新增，选出将要被删除的菜单
    * */
    let checkedKeys = RSService.getWillCheckedList(originCheckedListCopy, currentCheckedList);
    let unCheckedKeys = RSService.getWillDeletedList(originCheckedListCopy, currentUnCheckedList);
    let addlist = [];
    let deleteList = [];
    checkedKeys.map(item => {
      let key= item._originKey || item.key
      // 根节点不允许分配
      if( key !== 'ROOT' && key !== 'root'){
        addlist.push({
          "permissionId": cRole.id,
          "resourceId": item.resourceId,
          "operationType": "RW",
          "enabled": true,
          "functionCode": item._originKey || item.key
        })
      }
    });
    unCheckedKeys.map(item => {
      deleteList.push(item.__checkedId)
    });
    this.batchAddAndDelete(addlist, deleteList)
  };
  batchAddAndDelete = (addlist, deleteList) => {
    if(addlist.length || deleteList.length){
      this.setState({
        treeDataLoading: true
      })
      addlist.length && this.createPermissionTreeNodeBatch(addlist);
      deleteList.length && this.deletePermissionTreeNode(deleteList);
    }else {
      this.handleCancelFun()
    }
  }
  //新增批量菜单
  createPermissionTreeNodeBatch = (roleNodeList) => {
    RSService.createPermissionTreeNodeBatch(roleNodeList)
      .then(() => {
        this.itemSelect(true, this.state.cRole);
      })
      .catch(item => {
        this.handleCancelFun()
      })
  };
  //批量删除菜单
  deletePermissionTreeNode = (deleteList) => {
    RSService.deletePermissionTreeNodeBatch(deleteList)
      .then(res => {
        this.itemSelect(true, this.state.cRole);
      })
      .catch(item => {
        this.handleCancelFun()
      })
  };
  //删除菜单
  //不要提示了
  /*
  * @departed
  * */
  handleDeleteFun = (roleNodeList) => {
    Modal.confirm({
      title: messages('permission-setting.key13')/*确认*/,
      content: messages('permission-setting.key14')/*确认删除此菜单权限吗？*/,
      okText: messages('permission-setting.key13')/*确认*/,
      cancelText: messages('common.cancel')/*取消*/,
      onCancel: () => {
      },
      onOk: () => {
        this.deletePermissionTreeNode(roleNodeList);
      }
    });
  };
  //修改功能菜单
  updatePermissionTreeNode = (node) => {
    RSService.updatePermissionTreeNode(node)
      .then(() => {
        this.itemSelect(true, this.state.cRole);
      })
  };
  //不要勾选
  onUnChecked = (menu) => {
    let {allWithCheckedList, cRole} = this.state;
    if (cRole.permissionCode === "superAdmin") {
      message.warn(messages('permission-setting.key94')/*当前被操作的角色是超级管理员，不允许删除菜单*/);
      return;
    }
    allWithCheckedList.map(item => {
      if (item.resourceId === menu.resourceId) {
        item.__checked = false;
      }
    });
    let allWithCheckedListInstance = RSService.listTranformTree(allWithCheckedList);
    this.setState({
      allWithCheckedList: allWithCheckedListInstance.getOrigin(),
      allWithCheckedTree: this.handleCheckedAndShow(allWithCheckedListInstance.getResult())
    })
  }
  //勾选
  onChecked = (menu) => {
    let {allWithCheckedList} = this.state;
    allWithCheckedList.map(item => {
      if (item.resourceId === menu.resourceId) {
        item.__checked = true;
      }
    });
    let allWithCheckedListInstance = RSService.listTranformTree(allWithCheckedList);
    this.setState({
      allWithCheckedList: allWithCheckedListInstance.getOrigin(),
      allWithCheckedTree: this.handleCheckedAndShow(allWithCheckedListInstance.getResult())
    })
  }
  //渲染树形结构，所有可以被分配的菜单+已经被分配的菜单
  renderFunctionTree = (dataOrigin) => {
    let data = RSService.sortMenuList(dataOrigin, 'resourceOrder');
    return data.map((item, index) => {
      // if (item.children) {
      return (
        <TreeNode title={RSService.getRegisterNodeTitle(
          {
            item,
            onUnChecked: this.onUnChecked,
            onChecked: this.onChecked,
            editAble: this.state.editAble
          })}
          key={item.key}
          dataRef={item}>
          {item.children && this.renderFunctionTree(item.children)}
        </TreeNode>
      );
      // }
      // return <TreeNode title={RSService.getRegisterNodeTitle(
      //   {
      //     item,
      //     onUnChecked: this.onUnChecked,
      //     onChecked: this.onChecked,
      //     editAble: this.state.editAble
      //   }
      // )}
      //                  key={item.key}
      //                  dataRef={item}
      // />;
    });
  }
  //编辑模式
  showModalRole = () => {
    this.setState({
      editAble: true,
    })
  }
  //取消编辑模式
  handleCancelFun = () => {
    let {allWithCheckedListCopy} = this.state;
    let allWithCheckedListInstance = RSService.listTranformTree(allWithCheckedListCopy);
    this.setState({
      allWithCheckedList: allWithCheckedListInstance.getOrigin(),
      allWithCheckedTree: this.handleCheckedAndShow(allWithCheckedListInstance.getResult()),
      editAble: false,
      treeDataLoading: false
    })
  }

  // 不同角色选择树----end------
  render() {
    const {
      loading, cRole, expandedKeysRole, cNode, autoExpandParentRole, selectedKeysRole,
      treeDataLoading, allWithCheckedTree, editAble
    } = this.state;
    return (
      <div className="role-menu-setting-wrap">
        <div className='left-wrap f-left'>
          <RoleMenu
            menuLoading={treeDataLoading}
            onSelect={this.itemSelect}>
          </RoleMenu>
        </div>
        <div className="right-wrap">
          <div className="right-wrap-inner">
            <div className='title'>
              {cRole.permissionName}
            </div>
            <div className='btn-wrap'>
              <div className='left f-left'>
                {editAble && <Button type="primary"
                                     disabled={treeDataLoading}
                                     onClick={this.handleSaveFun}
                                     loading={loading}>
                  {messages("common.save")}
                </Button>}
                {editAble && <span>&nbsp;&nbsp;</span>}
                {editAble && <Button disabled={treeDataLoading}
                                     onClick={this.handleCancelFun}
                                     loading={loading}>
                  {messages("common.cancel")}
                </Button>}
                {!editAble && <Button type="primary"
                                      disabled={treeDataLoading}
                                      onClick={this.showModalRole}>
                  {treeDataLoading ? messages('permission-setting.key91')/*正在加载菜单*/ : messages('permission-setting.key95')/*编辑菜单*/}
                </Button>}
                &nbsp;&nbsp;  <Popover
                content={<div>{messages('permission-setting.key87')/*如果添加的一级菜单没有二级菜单，一级菜单将不显示*/}</div>}>
                <Icon className='meun-tips' type="info-circle"/>
              </Popover>
              </div>
              <div className='right f-right'>

              </div>
              <div className='clear'/>
            </div>
            <div className='permission-tree'>
              <div className="permission-tree-wrap f-left">
                <Search
                  placeholder={messages('permission-setting.key16')/*输入功能菜单名称*/}
                  onChange={this.fiterRoleList}
                  style={{width: 256, margin: 10}}
                />
                <div className='tree-wrap'>
                  <Spin spinning={treeDataLoading}>
                    {allWithCheckedTree && allWithCheckedTree.length > 0 ? <Tree
                      showLine
                      onExpand={this.onExpandRole}
                      expandedKeys={expandedKeysRole}
                      autoExpandParent={autoExpandParentRole}
                      onSelect={this.onSelectRole}
                      selectedKeys={selectedKeysRole}
                    >
                      {this.renderFunctionTree(allWithCheckedTree)}
                    </Tree> : <div className="permission-tree-empty-wrap">
                      {messages('permission-setting.key17')/*请添加功能菜单权限*/}
                    </div>}
                  </Spin>
                </div>

              </div>
              <div className="permission-tree-node-detail">
                <div className='i-permission-tree-node-detail'>
                  {cNode.resourceName && cNode.__checked ?
                    (<div key={cNode.resourceId}>
                      <h2>{cNode.resourceName}</h2>
                      <div className='content-wrap'>
                        {/* defaultReadable 为0 或者1 是不能选择切换的,为 2 的时候是可以切换 */}
                        <Select
                          style={{width: '200'}}
                          disabled={(cNode.defaultReadable + '') === '0' ||
                          (cNode.defaultReadable + '') === '1'}
                          value={cNode.operationType}
                          placeholder={messages("common.please.select")}
                          onChange={this.handleRoleOptionChange}
                        >
                          <Option value="RW">{messages('permission-setting.key48')/*可操作*/}</Option>
                          <Option value="R">{messages('permission-setting.key49')/*只读*/}</Option>
                        </Select>
                      </div>
                    </div>) : cNode.__checked ?
                      (<div>{messages('permission-setting.key18')/*请选择具体功能菜单进行操作*/}</div>) : (
                        <div>{messages('permission-setting.key96')/*请选择已经被分配的菜单进行操作*/}</div>)}
                </div>
              </div>
              <div className='clear'/>
            </div>
          </div>
        </div>
        <div className='clear'/>
      </div>
    )
  }
}

RoleMenuSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(RoleMenuSetting);
